package com.ruoyi.framework.util;

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class LoginCommonUtil {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysConfigService configService;

    /**
     * 校验验证码（支持不同登录类型）
     *
     * @param identifier 标识符（用户名或手机号）
     * @param code 验证码
     * @param uuid 唯一标识
     * @param loginType 登录类型（password-密码登录，sms-短信登录）
     * @return 结果
     */
    public void validateLoginCaptcha(String identifier, String code, String uuid) {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            if (captcha == null) {
                // 根据登录类型记录不同的日志信息
                String logMessage = MessageUtils.message("user.jcaptcha.expire");
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(identifier, Constants.LOGIN_FAIL, logMessage));
                throw new CaptchaExpireException();
            }
            redisCache.deleteObject(verifyKey);
            if (!code.equalsIgnoreCase(captcha)) {
                // 根据登录类型记录不同的日志信息
                String logMessage = MessageUtils.message("user.jcaptcha.error");
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(identifier, Constants.LOGIN_FAIL, logMessage));
                throw new CaptchaException();
            }
        }
    }


    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateRegisterCaptcha(String username, String code, String uuid) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            throw new CaptchaException();
        }
    }
}
